package com.sk.web.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.sk.util.SecurityDigest;
import com.sk.util.SecurityUtil;
import com.sk.util.SpringUtil;
import org.springframework.util.Assert;

import java.io.IOException;
import java.security.Key;

/**
 * 接口解密接收数据。
 *
 * @author smy
 * {@code @date} 2023/3/14
 */
public class AlgorithmDeserializer extends StdDeserializer<String> implements ContextualDeserializer {

    private String algorithm;

    private String key;
    private String keyData;
    private SecurityDigest digest;

    private AlgorithmDeserializer() {
        super(String.class);
    }

    protected AlgorithmDeserializer(AlgorithmDecoding annotation) {
        super(String.class);
        algorithm = annotation.algorithm();
        key = annotation.key();
        keyData = SpringUtil.getProperty(key);
        digest = annotation.digest();
    }


    @Override
    public AlgorithmDeserializer createContextual(DeserializationContext context, BeanProperty beanProperty) throws JsonMappingException {
        AlgorithmDecoding annotation = beanProperty.getAnnotation(AlgorithmDecoding.class);
        return new AlgorithmDeserializer(annotation);
    }

    @Override
    public String deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        Assert.notNull(keyData, "配置文件秘钥缺少：key=" + key);
        String source = parser.getText();
        Key key = SecurityUtil.loadDecodeKey(SecurityUtil.algorithm(algorithm), keyData);
        String value = SecurityUtil.decodeByCipher(algorithm, source, key);
        return digest.encode(value);
    }
}
